<template>
	<div :class="['h-selector',{'h-selector-active': show}]">
		<div class="h-selector-show" @click="showAddress">
			{{showValue || defaultShowValue}}
		</div>
		<transition name="h-selector-move">
			<div class="h-selector-container" v-if="show">
				<div class="h-selector-header">
					<div @click="cancel" class="h-selector-header-cancel">取消</div>
					<div class="h-selector-header-title">{{title}}</div>
					<div @click="confirm" class="h-selector-header-confirm">确定</div>
				</div>
				<div class="h-selector-content">
					<slot></slot>
					<div class="h-selector-bg"></div>
				</div>
			</div>
		</transition>
		<transition name="h-selector-fade">
			<div class="h-selector-layer" v-if="show" @click="cancel"></div>
		</transition>
	</div>
</template>

<script>
	export default {
		name: "hSelector",
		props: {
			value: {
				type: Object,
				required: true
			},
			showValue: {
				type: String,
			},
			title: {
				type: String,
				default: ''
			}
		},
		data() {
			let oldValue = Object.assign({}, this.value);
			return {
				oldValue,
				show: false
			}
		},
		computed: {
			defaultShowValue() {
				let arr = [];
				for (let i in this.value) {
					arr.push(i + ':' + this.value[i])
				}
				return arr.join('/');
			}
		},
		mounted() {
			this.$on('changeSelected', this.changeSelected);
		},
		methods: {
			changeSelected(prop, value) {
				let obj = {};
				obj[prop] = value;
				let obj2 = Object.assign({}, this.value, obj);
				this.$emit('input', obj2);
			},
			cancel() {
				this.$emit('input', this.oldValue);
				this.show = false;
			},
			confirm() {
				this.oldValue = Object.assign({}, this.value);
				this.$emit('change', this.value);
				this.show = false;
			},
			showAddress() {
				this.show = true;
			}
		}
	}
</script>
